﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.DirectoryServices;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Remoting;
using System.Management;
namespace WinUserAcc
{
    public class Common
    {

        public static  string Domain;
        public static SearchResult GetSearchResult(string psPath, string userName, string password)
        {
            try
            {

                var entry = new DirectoryEntry("LDAP://" + Common.Domain, userName, password, AuthenticationTypes.Secure);
                var searcher = new DirectorySearcher(entry) { Filter = string.Format("sAMAccountname=" + userName) };
                return searcher.FindOne();
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        ///启用ocs 2007
        /// </summary>
        /// <param name="samName">启用账号</param>
        /// <param name="emailAddress">邮箱地址</param>
        public static void EnableOCS(string samName, string emailAddress,string distinguishname)
        {

            //try
            //{
            //    ManagementClass UserClass = new ManagementClass(@"root\CIMV2", "MSFT_SIPESUSerSetting", null);

            //    var LCSSettings = UserClass.CreateInstance();
            //    LCSSettings["PrimaryUri"] = "sip:" + emailAddress;
            //    LCSSettings["Emabled"] = true;
            //    LCSSettings["HomeServerDN"] = "centaline";

            //    LCSSettings["UserDN"] = distinguishname;

            //    LCSSettings.Put();

                // var appSetting = appSettingClass.CreateInstance();

                //  appSetting["UserDN"] = "CN=" + samName + ",DC=centaline,DC=com,DC=cn";
                //  appSetting["HomeServerDN"] = "CN=LC Services,CN=Microsoft,CN=centapool,CN=RTC Service,CN=Microsoft,CN=System,DC=centaline,DC=com,DC=cn";
                //  appSetting["PrimaryURI"] = "sip:" + samName + "@centaline.com.cn";
                //  appSetting["Enabled"] = true;
                // // PutOptions opt = new PutOptions();
                //  //opt.Type = PutType.CreateOnly;
                //// appSetting.Put(opt);
                // appSetting.Put();
                //  appSetting.Dispose(); 
            //}
            //catch (Exception ex)
            //{

            //    throw ex;
            //}

            //try
            //{
            //    ManagementObject userOCSAccount = null; 
            //    SelectQuery userWMIQuery = new SelectQuery("SELECT * FROM MSFT_SIPESUserSetting");
            //    using (ManagementObjectSearcher wmiSearcher = new ManagementObjectSearcher(userWMIQuery))
            //    {
            //        foreach (ManagementObject searchResults in wmiSearcher.Get())
            //        {
            //            userOCSAccount = searchResults;
            //        }
            //    }
            //    userOCSAccount["LineURI"] = "tel:+14257064020";
            //    userOCSAccount["LocationProfile"] = "";
            //    userOCSAccount["UCPolicy"] = "";
            //    userOCSAccount["UCEnabled"] = false;

            //    //  Let’s save the changes back to OCS
            //    userOCSAccount.Put();
            //    userOCSAccount.Dispose();
            //    ////////////////////
            //    var stringBuilder = new StringBuilder();
            //    using (var powershell = PowerShell.Create())
            //    {

            //        var iss = InitialSessionState.CreateDefault();
            //        iss.AuthorizationManager = new AuthorizationManager("MyShellId");
            //        iss.ImportPSModule(new string[] { "Lync" });
            //        Runspace powerShellRunspace = RunspaceFactory.CreateRunspace(iss);
            //        powerShellRunspace.Open();

            //        powershell.Runspace = powerShellRunspace;
            //        powershell.AddCommand("Enable-OcsUser");
            //        powershell.AddParameter("Identity", samName);
            //        powershell.AddParameter("RegistrarPool", "lyncPoola.FQDN");
            //        powershell.AddParameter("SipAddressType", emailAddress);
            //        Collection<PSObject> results = powershell.Invoke();
            //        foreach (PSObject obj in results)
            //        {
            //            stringBuilder.AppendLine(obj.ToString());
            //        }
            //        powerShellRunspace.Close();
            //    }
            //    // return stringBuilder.ToString()
            //}
            //catch (Exception ex)
            //{
            //    throw ex;
            //}


        }
    }

    public class MailManager
    {
        /// <summary>
        /// 启用邮箱
        /// </summary>
        /// <param name="operName">创建者域账号</param>
        /// <param name="operPwd">创建者域密码</param>
        /// <param name="mail">要启用的邮箱账号的信息</param>
        public static void EnableMail(string operName, string operPwd, MailInfo mail)
        {
            var password = new SecureString();
            var strPassword = operPwd;
            var username = Common.Domain + "\\" + operName;
            string liveIdconnectionUri = "https://mail." + Common.Domain+ ".com.cn/Powershell?serializationLevel=Full";//链接邮箱域名

            foreach (var x in strPassword)
            {
                password.AppendChar(x);
            }

            var credential = new PSCredential(username, password);
            var connectionInfo = new WSManConnectionInfo((new Uri(liveIdconnectionUri)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);//Exchange邮箱
            connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

            var runspace = RunspaceFactory.CreateRunspace(connectionInfo);

            var powershell = PowerShell.Create();
            var command = new PSCommand();

            command.AddCommand("Enable-Mailbox");
            command.AddParameter("Identity", mail.SamAccountName);////要启用邮箱的账号
            // command.AddParameter("Name",mail.Name);
            command.AddParameter("Alias", mail.Alias);//'别名
            //  command.AddParameter("UserPrincipalName", mail.UserPrincipalName);
            // command.AddParameter("SamAccountName", mail.SamAccountName);
            //command.AddParameter("FirstName", mail.FirstName);
            //command.AddParameter("LastName", mail.LastName);
            //command.AddParameter("Password", mail.Password);
            //command.AddParameter("OrganizationalUnit", mail.OrganizationalUnit);
            // command.AddParameter("ResetPasswordOnNextLogon", mail.ResetPasswordOnNextLogon);
            // command.AddParameter("OrganizationalUnit", "centaline.com.cn/中原地产/AL.南京中原/ALB南京中原非营业部全体/ALBD.南京中原电脑部全体");
            // command.AddParameter("OrganizationalUnit",mail.OrganizationalUnit);
            //command.AddParameter("Memberof",
            //    "CN=南京中原电脑部全体,OU=ALL.南京中原电脑部全体,OU=ALB南京中原非营业部全体,OU=AL.南京中原,OU=中原地产,DC=centaline,DC=com,DC=cn");
            //command.AddParameter("Identity", "eforlina");
            command.AddParameter("Database", "Ex14CentaLimited100M02");//数据库
            // command.AddParameter("DomainController", "http://centaline.com.cn");

            powershell.Commands = command;
            try
            {
                runspace.Open(); //打开exchange邮箱
                powershell.Runspace = runspace;
                powershell.Invoke(); //执行
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
            finally
            {
                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
            }
        }

    }
}
